package pl.textureStudio.view.textureList
{
	import pl.textureStudio.model.StudioModel;
	import pl.textureStudio.data.vo.StudioTextureVO;
	import pl.textureStudio.view.panel.edit.TextureView;

	import utils.DimensionHelper;

	import flash.display.DisplayObjectContainer;
	import flash.display.Graphics;
	import flash.display.Shape;
	import flash.display.Sprite;
	import flash.events.MouseEvent;
	import flash.geom.Point;
	import flash.geom.Rectangle;

	/**
	 * @author michalr
	 */
	public class TextureItem extends Sprite
	{
		private var textureView:TextureView;
		private var margin:uint = 6;
		private var regionMask:Shape;
		private var regionData:Rectangle;
		private var textureID:String;
		public static const SIZE :uint = 128;
		
		public function TextureItem()
		{
			margin = Math.floor(SIZE * 0.016);
			var g:Graphics = graphics;
			g.beginFill( 0, 1 );
			g.drawRect( 0, 0, SIZE + margin, SIZE + margin );
			g.drawRect( margin, margin, SIZE - margin, SIZE - margin );
			g.endFill();
			g.lineStyle( 1, 0xFF0000 );
			g.moveTo( margin + SIZE / 2, margin );
			g.lineTo( margin + SIZE / 2, SIZE );
			g.moveTo( margin, margin + SIZE / 2 );
			g.lineTo( SIZE, margin + SIZE / 2 );
		}

		private function init():void
		{
			addChild( textureView );
			var area:Point = new Point( SIZE, SIZE );
			var s:Number;
			s = DimensionHelper.fitObjectInArea( textureView.getSize(), area );
			textureView.scaleX = textureView.scaleY = s;
			var px:uint = margin + Math.floor( (area.x - textureView.getSize().x * s) * .5 );
			var py:uint = margin + Math.floor( (area.y - textureView.getSize().y * s) * .5 );
			// ...
			if (regionData != null)
			{
				px = margin + Math.floor( (area.x ) * .5 - (regionData.x + regionData.width * .5 ) * s );
				py = margin + Math.floor( (area.y ) * .5 - (regionData.y + regionData.height * .5) * s );
				regionMask = new Shape();
				addChild( regionMask );
				regionMask.x = Math.floor( px + regionData.x * s );
				regionMask.y = Math.floor( py + regionData.y * s );
				regionMask.graphics.beginFill( 0 );
				regionMask.graphics.drawRect( 0, 0, Math.floor( regionData.width * s ), Math.floor( regionData.height * s ) );
				textureView.mask = regionMask;
			}

			textureView.x = px;
			textureView.y = py;
			addEventListener( MouseEvent.CLICK, onClick );
		}

		private function onClick( event:MouseEvent ):void
		{
			StudioModel.getInstance().editTextureByID(textureID);
		}

		public static function factory( parent:DisplayObjectContainer, vo:StudioTextureVO ):TextureItem
		{
			var o:TextureItem = new TextureItem();
			o.textureID = vo.textureID;
			o.textureView = TextureView.factory( vo );
			if (vo.texturePackRegion != null) o.regionData = vo.texturePackRegion;
			o.init();
			parent.addChild( o );
			return o;
		}
	}
}
